{
 "nbformat": 4,
 "nbformat_minor": 0,
 "metadata": {
  "colab": {
   "provenance": [
    {
     "file_id": "19HZxXKTbH3gIcFXt5X3NJyj1HIH7dFVm",
     "timestamp": 1669899770792
    },
    {
     "file_id": "1evQYjB3EsMPc5naRj12jur1fWrIoXGKR",
     "timestamp": 1668049627053
    },
    {
     "file_id": "1uqFmyhthsoQUohWeoaLQItjIxszx0mbM",
     "timestamp": 1651113592749
    }
   ]
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Project 1\n",
    "# Volatility Breakout Strategy\n",
    "\n",
    "#### 2022-2학기\n",
    "#### Version: 2022-11-11-v1\n",
    "\n",
    "> 분반:\n",
    ">\n",
    "> 학번:\n",
    ">\n",
    "> 학과:\n",
    ">\n",
    "> 이름:\n",
    "\n",
    "\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "# 런타임이 종료되면 이 코드셀은 매번 다시 실행해야 합니다. 译：runtime结束后，这个coad cell每次都要重新运行。\n",
    "# pyupbit 설치 译：设置pyupbit\n",
    "!pip install pyupbit"
   ],
   "metadata": {
    "id": "iY-TEVpkSEJ4"
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "source": [
    "# Import\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import datetime\n",
    "\n",
    "import pyupbit\n"
   ],
   "metadata": {
    "id": "hYFModET9l9c"
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "source": [
    "# trading_helper 설치 및 버전 확인 译：# trading_helper 设置和版本确认\n",
    "\n",
    "!wget https://esohn.be/python/trading_helper.py -O trading_helper.py\n",
    "\n",
    "import trading_helper\n",
    "import importlib\n",
    "importlib.reload(trading_helper)\n",
    "\n",
    "print( f'Trading Helper Version: {trading_helper.TRADING_HELPER_VERSION}'  )"
   ],
   "metadata": {
    "id": "cS8gx8ljNiyv"
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------------------------------------------------------\n",
    "# https://esohn.be/account 의 AUTH CODE 입력 译：https://esohn.be/account 的 AUTH CODE 输入\n",
    "# ------------------------------------------------------------------------------------------------------\n",
    "'''\n",
    "AUTH_CODE = 'f587ea651febd5446efc61d5e3fef123'  -> 아래에 이렇게 auth code를 붙여넣으세요. 译：请在下面这样粘贴auth code\n",
    "'''\n",
    "AUTH_CODE = '2319d129e17e2cd365363ef4ebfb4596'\n",
    "\n",
    "# Do not edit\n",
    "trading_helper.set_auth_code( AUTH_CODE )\n"
   ],
   "metadata": {
    "id": "NyKvER304v4w"
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 아래 코드셀을 복사해서 프로젝트 코드로 붙여 넣으세요.\n",
    "### 译：复制下面的代码单元并粘贴到项目代码中。"
   ],
   "metadata": {
    "id": "s7SilAF8Y5oo"
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "fjauVJp1SB8f"
   },
   "outputs": [],
   "source": [
    "# ------------------------------------------------------------------------------------------------------\n",
    "# - 코드를 완성했다면 이 코드셀만 복사해서 competition 페이지 Volatility Breakout 탭에 라운드 별 코드 항목으로 붙여넣습니다.\n",
    "# - 연습할 때는 https://esohn.be/competition 페이지의 에디터에서 직접 연습하지 말고 Colab에서 연습하세요. \n",
    "#   (노트북 연습 횟수가 서버에 기록되며 또 노트북 자체에 변경 history가 축척 됩니다.)\n",
    "#译：\n",
    "#完成代码后，只需复制此代码单元（code cell）并将其作为每轮代码条目粘贴到competition页面的“Volatility Breakout”中。\n",
    "#练习的时候不要在https://esohn.be/competition页面的编辑, 请在Colab里练习\n",
    "#（笔记本电脑练习次数将被记录在服务器上，笔记本电脑本身也会积累变更history。）\n",
    "# ------------------------------------------------------------------------------------------------------\n",
    "\n",
    "# Given Code Version 2022.11.10-v1\n",
    "\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import datetime\n",
    "\n",
    "\n",
    "# [프로젝트 1]\n",
    "# volatility_breakout() 변동성 돌파 전략 함수 \n",
    "#\n",
    "# df - 일별 가격 정보를 가지고 있는 데이터 프레임\n",
    "# k - k값, 기본값은 0.5\n",
    "#\n",
    "# Qualification 라운드 에서는 상승장 구분을 사용하지 않음 (df['cond2'] = True로 남겨둠)\n",
    "# 그 외의 라운드에서는 원하는 k값과 상승장 구분을 사용하여 경쟁\n",
    "\n",
    "#译：[项目1]\n",
    "#    volatility_breakout() 变动性突破战略函数\n",
    "#    df - 具有每日价格信息的数据框架\n",
    "#    k - k 值， 默认值（基本值）为 0.5\n",
    "#    Qualification 回合中不使用 上升场（bull market？） 分类 (df['cond2'] = 保留为True)\n",
    "#\n",
    "def volatility_breakout( df, k=0.5 ):\n",
    "\n",
    "    if k < 0:\n",
    "        return\n",
    "        \n",
    "    # 전일 레인지 range_s = (고가 - 저가).shift(1)\n",
    "    #译：前一天的range  range_s = (高价 - 低价).shift(1)\n",
    "    df['range_s'] = (df['high'] - df['low']).shift(1) # EDIT (1)\n",
    "\n",
    "    # 목표 매수가 = 오늘 시가 + 전일 레인지 * k\n",
    "    #译：目标买入 = 今日市价 + 前一天的range * k\n",
    "    df['target'] = df['open'] + df['range_s']*k # EDIT (2)\n",
    "\n",
    "    # 먄약 이동평균을 활용하고 싶으면 다음과 같이 이동평균 열을 추가\n",
    "    #译：如果想使用moving average，请添加以下 moving average 列\n",
    "    # df['ma5'] = df['close'].rolling(5).mean().shift(1)\n",
    "    # df['ma20'] = df['close'].rolling(20).mean().shift(1)\n",
    "    # df['ma50'] = df['close'].rolling(50).mean().shift(1)\n",
    "\n",
    "    #--------------------------------------------------------------\n",
    "    # 조건 1 - 변동성 돌파 ( np.where( 고가 >= 목표 매수가, True, False ) )\n",
    "    #译：条件 1 - 突破变动性 (np.where(高价 > = 目标收购, True, False))\n",
    "    '''\n",
    "    cond1 에는 변동성 돌파 전략을 위한 수식만 사용 가능합니다.\n",
    "    译：cond1只能使用用于可变性突破策略的公式。\n",
    "    '''\n",
    "\n",
    "    df['cond1'] = False # EDIT (3)\n",
    "    #--------------------------------------------------------------\n",
    "\n",
    "    #--------------------------------------------------------------\n",
    "    # 조건 2 - 상승장 구분 (optional)\n",
    "    #译：条件 2 - 区分上升场 (optional)\n",
    "    #\n",
    "    # 추가 조건이 없다면, 译：如果没有追加的条件的话\n",
    "    #   df['cond2'] = True \n",
    "    # 5일 이동평균보다 시가가 높을 때만 매매한다면, 译：如果只在市价高于5日移动平均值（moving average）时进行交易，\n",
    "    #   df['cond2'] = np.where( (df['open'] >= df['ma5']), True, False )\n",
    "    # 3일 이동평균 및 5일 이동평균보다 시가가 높을 때만 매매한다면, 译：如果仅在市价高于3天移动平均值和5天移动平均值时进行交易，\n",
    "    #   df['cond2'] = np.where( (df['open'] >= df['ma3']) & (df['open'] >= df['ma5']), True, False )\n",
    "    # \n",
    "    '''\n",
    "    cond2 에서 open 이외에 오늘 결정되지 않은 미래의 정보(close, high, low, volume)를 그냥 사용하면 안됩니다.\n",
    "    译：在cond2中,除了open之外,不能直接使用今天没有决定的未来信息(close, high, low, volume)。\n",
    "    .shift(1) 를 붙이면 모두 사용 가능합니다.\n",
    "    译：粘贴了shift(1)即都可使用。\n",
    "\n",
    "    예를 들어,（ 比如）\n",
    "    - df['open'] : 사용 가능（可以使用） \n",
    "    - df['close'].shift(1) : 사용 가능（可以使用）\n",
    "    - df['high'] : 사용 불가능（不可以使用）\n",
    "    - df['low'].shift(1) : 사용 가능（可以使用）\n",
    "    - df['close'].shift(2) : 사용 가능（可以使用）\n",
    "    '''\n",
    "    \n",
    "    df['cond2'] = True # EDITABLE\n",
    "    print(df)\n",
    "    #--------------------------------------------------------------\n",
    "\n",
    "    return df\n",
    "\n",
    "# 이 코드 셀은 함수 정의 이외에는 다른 내용을 아래에 덧붙이지 마세요.\n",
    "#译：这个code cell（代码单元）除了函数定义以外，不要在下面添加其他内容。\n",
    "# ------------------------------------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 가격정보 가져오기（获取价格信息）"
   ],
   "metadata": {
    "id": "uFEL4omTY_Tr"
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "data": {
      "text/plain": "                  Unnamed: 0        open        high         low       close  \\\n0  2021-04-01 09:00:00+09:00  71480000.0  73325000.0  71032000.0  72749000.0   \n1  2021-04-02 09:00:00+09:00  72749000.0  74400000.0  71841000.0  73855000.0   \n2  2021-04-03 09:00:00+09:00  73934000.0  75703000.0  71783000.0  72187000.0   \n3  2021-04-04 09:00:00+09:00  72187000.0  74240000.0  71570000.0  73974000.0   \n4  2021-04-05 09:00:00+09:00  73908000.0  78780000.0  73890000.0  78770000.0   \n\n         volume         value  \n0   9170.381958  6.630544e+11  \n1   8712.294082  6.413909e+11  \n2   9274.318109  6.892717e+11  \n3   6583.438203  4.821920e+11  \n4  13425.681678  1.019472e+12  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2021-04-01 09:00:00+09:00</td>\n      <td>71480000.0</td>\n      <td>73325000.0</td>\n      <td>71032000.0</td>\n      <td>72749000.0</td>\n      <td>9170.381958</td>\n      <td>6.630544e+11</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2021-04-02 09:00:00+09:00</td>\n      <td>72749000.0</td>\n      <td>74400000.0</td>\n      <td>71841000.0</td>\n      <td>73855000.0</td>\n      <td>8712.294082</td>\n      <td>6.413909e+11</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2021-04-03 09:00:00+09:00</td>\n      <td>73934000.0</td>\n      <td>75703000.0</td>\n      <td>71783000.0</td>\n      <td>72187000.0</td>\n      <td>9274.318109</td>\n      <td>6.892717e+11</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2021-04-04 09:00:00+09:00</td>\n      <td>72187000.0</td>\n      <td>74240000.0</td>\n      <td>71570000.0</td>\n      <td>73974000.0</td>\n      <td>6583.438203</td>\n      <td>4.821920e+11</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2021-04-05 09:00:00+09:00</td>\n      <td>73908000.0</td>\n      <td>78780000.0</td>\n      <td>73890000.0</td>\n      <td>78770000.0</td>\n      <td>13425.681678</td>\n      <td>1.019472e+12</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 가격정보 가져오기 （获取价格信息）\n",
    "from_date = '20210401'\n",
    "to_date = '20221101'\n",
    "\n",
    "df = trading_helper.get_ohlcv2('KRW-BTC', date1=from_date, date2=to_date )\n",
    "\n",
    "df.head()\n"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### k=0.5, 0.8일 때의 HPR, MDD （k=0.5、0.8时的HPR、MDD）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'volatility_breakout' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mNameError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[4], line 3\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;66;03m# 함수 테스트 （函数测试）\u001B[39;00m\n\u001B[0;32m      2\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mtrading_helper\u001B[39;00m\n\u001B[1;32m----> 3\u001B[0m \u001B[43mvolatility_breakout\u001B[49m( df, \u001B[38;5;241m0.5\u001B[39m )\n\u001B[0;32m      5\u001B[0m hpr, mdd \u001B[38;5;241m=\u001B[39m trading_helper\u001B[38;5;241m.\u001B[39mcheck_performance_vol( df )\n\u001B[0;32m      7\u001B[0m \u001B[38;5;28mprint\u001B[39m( \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mHPR = \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mhpr \u001B[38;5;241m*\u001B[39m \u001B[38;5;241m100\u001B[39m\u001B[38;5;132;01m:\u001B[39;00m\u001B[38;5;124m.1f\u001B[39m\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m%, MDD = \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mmdd \u001B[38;5;241m*\u001B[39m \u001B[38;5;241m100\u001B[39m\u001B[38;5;132;01m:\u001B[39;00m\u001B[38;5;124m.1f\u001B[39m\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m%\u001B[39m\u001B[38;5;124m'\u001B[39m )\n",
      "\u001B[1;31mNameError\u001B[0m: name 'volatility_breakout' is not defined"
     ]
    }
   ],
   "source": [
    "# 함수 테스트 （函数测试）\n",
    "volatility_breakout( df, 0.5 )\n",
    "\n",
    "hpr, mdd = trading_helper.check_performance_vol( df )\n",
    "\n",
    "print( f'HPR = {hpr * 100:.1f}%, MDD = {mdd * 100:.1f}%' )\n",
    "\n",
    "volatility_breakout( df, 0.8 )\n",
    "\n",
    "hpr, mdd = trading_helper.check_performance_vol( df )\n",
    "\n",
    "print( f'HPR = {hpr * 100:.1f}%, MDD = {mdd * 100:.1f}%' )"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### HPR 그래프 （HPR图）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'hpr'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mKeyError\u001B[0m                                  Traceback (most recent call last)",
      "File \u001B[1;32m~\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\pandas\\core\\indexes\\base.py:3803\u001B[0m, in \u001B[0;36mIndex.get_loc\u001B[1;34m(self, key, method, tolerance)\u001B[0m\n\u001B[0;32m   3802\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m-> 3803\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_engine\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mget_loc\u001B[49m\u001B[43m(\u001B[49m\u001B[43mcasted_key\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m   3804\u001B[0m \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mKeyError\u001B[39;00m \u001B[38;5;28;01mas\u001B[39;00m err:\n",
      "File \u001B[1;32m~\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\pandas\\_libs\\index.pyx:138\u001B[0m, in \u001B[0;36mpandas._libs.index.IndexEngine.get_loc\u001B[1;34m()\u001B[0m\n",
      "File \u001B[1;32m~\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\pandas\\_libs\\index.pyx:165\u001B[0m, in \u001B[0;36mpandas._libs.index.IndexEngine.get_loc\u001B[1;34m()\u001B[0m\n",
      "File \u001B[1;32mpandas\\_libs\\hashtable_class_helper.pxi:5745\u001B[0m, in \u001B[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001B[1;34m()\u001B[0m\n",
      "File \u001B[1;32mpandas\\_libs\\hashtable_class_helper.pxi:5753\u001B[0m, in \u001B[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001B[1;34m()\u001B[0m\n",
      "\u001B[1;31mKeyError\u001B[0m: 'hpr'",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001B[1;31mKeyError\u001B[0m                                  Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[10], line 3\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;66;03m# 기간 수익률(HPR) 변화 추이 그래프 （# 期收益率(HPR)变化趋势图）\u001B[39;00m\n\u001B[1;32m----> 3\u001B[0m ( (\u001B[43mdf\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[38;5;124;43mhpr\u001B[39;49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[43m]\u001B[49m\u001B[38;5;241m-\u001B[39m\u001B[38;5;241m1\u001B[39m) \u001B[38;5;241m*\u001B[39m \u001B[38;5;241m100\u001B[39m)\u001B[38;5;241m.\u001B[39mplot( figsize\u001B[38;5;241m=\u001B[39m(\u001B[38;5;241m15\u001B[39m,\u001B[38;5;241m3\u001B[39m) )\n",
      "File \u001B[1;32m~\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\pandas\\core\\frame.py:3804\u001B[0m, in \u001B[0;36mDataFrame.__getitem__\u001B[1;34m(self, key)\u001B[0m\n\u001B[0;32m   3802\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mcolumns\u001B[38;5;241m.\u001B[39mnlevels \u001B[38;5;241m>\u001B[39m \u001B[38;5;241m1\u001B[39m:\n\u001B[0;32m   3803\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_getitem_multilevel(key)\n\u001B[1;32m-> 3804\u001B[0m indexer \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcolumns\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mget_loc\u001B[49m\u001B[43m(\u001B[49m\u001B[43mkey\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m   3805\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m is_integer(indexer):\n\u001B[0;32m   3806\u001B[0m     indexer \u001B[38;5;241m=\u001B[39m [indexer]\n",
      "File \u001B[1;32m~\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\pandas\\core\\indexes\\base.py:3805\u001B[0m, in \u001B[0;36mIndex.get_loc\u001B[1;34m(self, key, method, tolerance)\u001B[0m\n\u001B[0;32m   3803\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_engine\u001B[38;5;241m.\u001B[39mget_loc(casted_key)\n\u001B[0;32m   3804\u001B[0m \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mKeyError\u001B[39;00m \u001B[38;5;28;01mas\u001B[39;00m err:\n\u001B[1;32m-> 3805\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mKeyError\u001B[39;00m(key) \u001B[38;5;28;01mfrom\u001B[39;00m \u001B[38;5;21;01merr\u001B[39;00m\n\u001B[0;32m   3806\u001B[0m \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mTypeError\u001B[39;00m:\n\u001B[0;32m   3807\u001B[0m     \u001B[38;5;66;03m# If we have a listlike key, _check_indexing_error will raise\u001B[39;00m\n\u001B[0;32m   3808\u001B[0m     \u001B[38;5;66;03m#  InvalidIndexError. Otherwise we fall through and re-raise\u001B[39;00m\n\u001B[0;32m   3809\u001B[0m     \u001B[38;5;66;03m#  the TypeError.\u001B[39;00m\n\u001B[0;32m   3810\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_check_indexing_error(key)\n",
      "\u001B[1;31mKeyError\u001B[0m: 'hpr'"
     ]
    }
   ],
   "source": [
    "# 기간 수익률(HPR) 변화 추이 그래프 （# 期收益率(HPR)变化趋势图）\n",
    "\n",
    "( (df['hpr']-1) * 100).plot( figsize=(15,3) )"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### MDD 그래프 （MDD图）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 낙폭(Drawdown) 변화 추이 그래프 （# 降幅变化趋势图）\n",
    "\n",
    "(-df['dd'] * 100).plot( figsize=(15,3) )"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 여러 개의 k값을 시도해보고 싶을 때 （想要尝试多个k值时）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 여러개의 k값을 시도해보고 싶을 때 （想要尝试多个k值时）\n",
    "\n",
    "records = [];\n",
    "\n",
    "for k in np.arange(0.4, 0.5, 0.02):\n",
    "\n",
    "    volatility_breakout( df, k )\n",
    "\n",
    "    hpr, mdd = trading_helper.check_performance_vol( df )\n",
    "\n",
    "    records.append( ( hpr * 100, mdd * 100, k) )\n",
    "\n",
    "records.sort(reverse=True)\n",
    "\n",
    "for record in records:\n",
    "    print(f'HPR= {record[0]:.1f}% MDD= {record[1]:.1f}% k= {record[2]:.2f}')\n"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ]
}
